<?php
namespace app\index\controller;

use think\Controller;
use think\Db;
use think\Request;
use think\Session;
use think\config;
use Qiniu\Auth as Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;

class User extends Controller
{
    public function index()
    {

        $session = Session::get();


        $id = $session['hmy_user']['id'];


        // 一级分类
        $category = DB::table('category')->where('pid','0,')->select();



        // 查询关注
        $follow = Db::table(['follow' =>'f','hmy_user' =>'u','users_follow'=>'uf'])
                    // 关注表的用户id = 用户关注表的用户id  用户id = 用户关注表的关注id
                    ->where('f.id = uf.fid && u.id = uf.uid && uf.uid = '.$id)
                    // 查询用户关注了多少人
                    ->field('uf.fid')
                    ->select();

        // 关注数量
        $follow_num = count($follow);





        // 查询粉丝
        $fans = Db::table(['fans' =>'f','hmy_user' =>'u','users_fans'=>'uf'])
                    ->where('f.id = uf.fid && u.id = uf.uid && uf.uid = '.$id)
                    ->field('uf.fid')
                    ->select();

        // 关注数量
        $fans_num = count($fans);




        // 查询收藏
        $like = Db::table(['picture' =>'p','like'=>'l'])
                    ->where('p.user_id = l.user_id && l.pict_id = p.id && p.user_id= '.$id)
                    ->field('l.pict_id')
                    ->select();

        // 关注数量
        $like = count($like);



        // 遍历分类(添加)
        $res = Db::table('category')
                    ->order('path', 'id')
                    ->select();

        // 查询作品
        $list = Db::table(['picture' => 'p','category'=>'c'])
                    ->where('c.id = p.cate_id && user_id ='.$id)
                    ->limit(4)
                    ->order('p.id','desc')
                    ->select();
        // var_dump($list);

        // 查询收藏

        return view('index@user/index',[
            'session' => $session,
            'category' => $category,
            'follow_num' => $follow_num,
            'fans_num' => $fans_num,
            'like_num' => $like,
            'list' => $list,
            'res' => $res
        ]);
    }

    // 加载更多的图片
    public function more()
    {
        $session = Session::get('hmy_user');
        // var_dump($session);die;
        $id = $session['id'];

        $category = DB::table('category')->where('pid','0,')->select();

        $list = Db::table(['picture' => 'p','category'=>'c'])
                    ->where('c.id = p.cate_id && user_id ='.$id)
                    ->order('p.id','desc')
                    ->select();
        // var_dump($list);die;
        return view('index@user/more',['session' => $session,'category' => $category,'list' => $list]);
    }

    // 删除图片
    public function delete($id)
    {
        $list = Db::table('picture')
                    ->where('id',$id)
                    ->delete();
        if($list){
            return  $this->success('删除图片成功');
        }else{
            return  $this->success('删除图片失败');
        }
    }

    // 修改资料
    public function edit()
    {
        $session = Session::get('hmy_user');

        $category = DB::table('category')->where('pid','0,')->select();

        return view('index@user/edit',['session' => $session,'category' => $category]);
    }


    // 执行修改资料
    public function doEdit(Request $request)
    {

        // 接收数据
        $data = $request->post();

        // 获取id
        $id = $request->post('id');

        $file = $request->file('file');

        // 要上传图片的本地路径
        $filePath = $file->getRealPath();

        $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀

        $img = ['png', 'jpg', 'jpeg'];

        if (!in_array($ext, $img)){

            return $this->error('上传的文件必须为图片格式!');

        }


        // 上传到七牛后保存的文件名
        $key = substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext;

        // 需要填写 Access Key 和 Secret Key
        $accessKey = Config::get('qiniu.accessKey');
        $secretKey = Config::get('qiniu.secretKey');

        // 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);

        // 要上传的空间
        $bucket = Config::get('qiniu.bucket');
        $domain = Config::get('qiniu.DOMAIN');

        $token = $auth->uploadToken($bucket);

        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new UploadManager();

        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);


        $data['icon'] = $ret['key'];

        // 执行sql语句
        $result = Db::table('hmy_user')->where('id', $id)->update($data);

        // 返回
       if ($result > 0) {

            // 更新session
            Session::set('hmy_user',$data);
           return $this->success('保存成功..', url('index/User/index'));

       } else {

           return $this->error('保存失败,请重试...');

       }
    }


    // 修改密码
    public function pass()
    {
        $session = Session::get('hmy_user');
        // var_dump($session);

        $id = $session['id'];

        $category = DB::table('category')->where('pid','0,')->select();

        return view('index@user/editPass',['session' => $session,'category' => $category]);
    }


    // 执行修改密码
    public function doPass(Request $request)
    {
        // 接收数据
        $post = $request->post();

        // 获取id
        $id = $request->post('id');

        // 查询数据
        $data = DB::table('hmy_user')->find($id);
        // var_dump($data);die;

        // 判断原密码
        if (md5($post['ypass']) != $data['pass']) {

            return $this->error('原密码错误,请重新输入...');

        }

        // 判断两次密码
        if ($post['pass'] != $post['repass']) {

            return $this->error('两次密码不一致,请重新输入...');

        }

        // 判断原密码和新密码是否一致
        if (md5($post['pass']) == $data['pass']) {

            return $this->error('新密码和原密码不能为一致,请重新输入...');

        }

        // 加密
        $post['pass'] = md5($post['pass']);



        // 删除原密码和重复密码
        unset($post['repass']);
        unset($post['ypass']);


        // 执行sql语句
        $result = Db::table('hmy_user')->where('id', $id)->update($post);

        // 返回
       if ($result > 0) {

            // 更新session
            Session::set('hmy_user',$data);
           return $this->success('修改成功,请重新登录', url('index/Login/index'));

       } else {

           return $this->error('保存失败,请重试...');

       }
    }



    // 粉丝页面
    public function fans()
    {
        $session = Session::get();


        $id = $session['hmy_user']['id'];

        // 一级分类
        $category = DB::table('category')->where('path','0,')->select();


        // 查询粉丝
        $fans = Db::table(['fans' =>'f','hmy_user' =>'u','users_fans'=>'uf'])
                    ->where('f.id = uf.fid && u.id = uf.uid && uf.uid = '.$id)
                    ->field('f.iconname,f.sex,f.icon,u.status,f.user_id,f.black,f.id')
                    ->select();

        // var_dump($fans);

        // 粉丝数量
        $fans_num = count($fans);


        return view('index@user/fans',[
            'session' => $session,
            'category' => $category,
            'fans' => $fans,
            'fans_num' => $fans_num
        ]);

    }


    // 粉丝拉黑
    public function blackList($uid)
    {

        $session = Session::get();

        $id = $session['hmy_user']['id'];
        // var_dump($id);



        // 查询粉丝
        $fans = Db::table(['fans' =>'f','users_fans'=>'uf'])
                    ->where('f.id = uf.fid && uf.uid = '.$id.' && f.user_id = '.$uid)
                    ->field('f.iconname,f.sex,f.icon,f.user_id,f.black')
                    ->select();


        $fans['0']['black'] = $fans['0']['black'] == '1'?'2':'1';

        // var_dump($fans);die;

       $result = Db::table('fans')->where('user_id = '.$uid)->update($fans[0]);

       // 跳转
       if ($result > 0) {

           $this->redirect('index/User/fans');;

       }
    }


    // 查看粉丝资料
    public function toview($uid)
    {

        $session = Session::get();

        // $id = $uid;

        // 一级分类
        $category = DB::table('category')->where('pid','0,')->select();

        // 查询资料
        $user = DB::table('hmy_user')->where('id',$uid)->find();


        // 查询关注
        $follow = Db::table(['follow' =>'f','hmy_user' =>'u','users_follow'=>'uf'])
                    ->where('f.id = uf.fid && u.id = uf.uid && uf.uid = '.$uid)
                    ->field('uf.fid')
                    ->select();


        // 关注数量
        $follow_num = count($follow);

        // 查询粉丝
        $fans = Db::table(['fans' =>'f','hmy_user' =>'u','users_fans'=>'uf'])
                    ->where('f.id = uf.fid && u.id = uf.uid && uf.uid = '.$uid)
                    ->field('uf.fid')
                    ->select();

        // var_dump($fans);die;


        // 关注数量
        $fans_num = count($fans);


        // 查询粉丝
        $like = Db::table(['picture' =>'p','hmy_user' =>'u','like'=>'l'])
                    ->where('p.user_id = l.user_id && u.id = l.user_id && l.user_id= '.$uid)
                    ->field('l.pict_id')
                    ->select();

        // var_dump($like);


        // 关注数量
        $like = count($like);


        // 遍历分类(上传)
        $res = Db::table('category')
                    ->order('path', 'id')
                    ->select();

        // 粉丝的作品
        $list = Db::table('picture')
                    ->where('user_id ='.$uid)
                    ->select();



        // 查询收藏



        // 返回
        return view('index@user/fansindex',[
            'session' => $session,
            'category' => $category,
            'follow_num' => $follow_num,
            'fans_num' => $fans_num,
            'like_num' => $like,
            'list' => $list,
            'res' => $res,
            'user' => $user
        ]);
    }



    // 粉丝的粉丝页面
    public function viewfans($id)
    {
        $session = Session::get();

        // 一级分类
        $category = DB::table('category')->where('path','0,')->select();


        // 查询粉丝
        $fans = Db::table(['fans' =>'f','hmy_user' =>'u','users_fans'=>'uf'])
                    ->where('f.id = uf.fid && u.id = uf.uid && uf.uid = '.$id)
                    ->field('f.iconname,f.sex,f.icon,u.status,f.user_id,f.black')
                    ->select();

        // var_dump($fans);die;

        // 粉丝数量
        $fans_num = count($fans);


        return view('index@user/viewfans',[
            'session' => $session,
            'category' => $category,
            'fans' => $fans,
            'fans_num' => $fans_num
        ]);
    }


    // 粉丝的关注页面
    public function viewfollow($id)
    {
        $session = Session::get();


        // 一级分类
        $category = DB::table('category')->where('path','0,')->select();


        // 查询关注

        $follow = Db::table(['follow' =>'f','hmy_user' =>'u','users_follow'=>'uf'])
                    ->where('f.id = uf.fid && u.id = uf.uid && uf.uid = '.$id)
                    ->field('f.iconname,f.sex,f.icon,u.status,f.user_id')
                    ->select();

        // var_dump($follow);die;

        // 关注数量
        $follow_num = count($follow);


        return view('index@user/viewfollow',[
            'session' => $session,
            'category' => $category,
            'follow' => $follow,
            'follow_num' => $follow_num
        ]);
    }


    // 关注页面
    public function follow()
    {
        $session = Session::get();


        $id = $session['hmy_user']['id'];

        // 一级分类
        $category = DB::table('category')->where('path','0,')->select();


        // 查询关注

        $follow = Db::table(['follow' =>'f','hmy_user' =>'u','users_follow'=>'uf'])
                    ->where('f.id = uf.fid && u.id = uf.uid && uf.uid = '.$id)
                    ->field('f.iconname,f.sex,f.icon,u.status,f.user_id,f.id')
                    ->select();

        // var_dump($follow);

        // 关注数量
        $follow_num = count($follow);


        return view('index@user/follow',[
            'session' => $session,
            'category' => $category,
            'follow' => $follow,
            'follow_num' => $follow_num

        ]);


    }




    // 取消关注
    public function cancel($uid)
    {
        // var_dump($uid);

        $session = Session::get();

        $id = $session['hmy_user']['id'];


        // 查询关注
        $follow = Db::table(['follow' =>'f','users_follow'=>'uf'])
                    ->where('f.id = uf.fid && uf.uid = '.$id.' && f.user_id = '.$uid)
                    ->field('f.iconname,f.sex,f.icon,f.user_id,f.id')
                    ->select();

        // 关注表的ID
        $f_id = $follow[0]['id'];

        // var_dump($follow);die;

        // 删除用户关注表id
        $res = Db::table('users_follow')->where($f_id.' = fid && uid = '.$id)->delete();

        // 删除关注表
        $result = Db::table('follow')->where($f_id.' = id && user_id = '.$uid)->delete();

       // 跳转
       if ($result > 0) {

           $this->redirect('index/User/follow');;

       }

    }



     // 上传图片
    public function detiles()
    {

        // 用户id
        $session = Session::get();

        $id = $session['hmy_user']['id'];


        // var_dump($_POST);
        //接收文件
        $file = request()->file('file');
        // var_dump($file);die;

        $file = empty($file)?$this->error('请上传您的文件'): $file;

        // 要上传图片的本地路径
        $filePath = $file->getRealPath();

        $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀


        $img = ['png', 'jpg', 'jpeg'];

        if (!in_array($ext, $img)){

            return $this->error('上传的文件必须为图片格式!');

        }


        // 上传到七牛后保存的文件名
        $key = substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext;

        // 需要填写 Access Key 和 Secret Key
        $accessKey = Config::get('qiniu.accessKey');
        $secretKey = Config::get('qiniu.secretKey');

        // 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);

        // 要上传的空间
        $bucket = Config::get('qiniu.bucket');
        $domain = Config::get('qiniu.DOMAIN');

        $token = $auth->uploadToken($bucket);

        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new UploadManager();

        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);

        if($err == null){
            // 这一块要变成自己数据表需要的字段
            $url ="http://phv2jzzej.bkt.clouddn.com/".$ret['key'];

            $list['src'] = $ret['key'];

            $list['cate_id'] = $_POST['cid'];

            $list['title'] = $_POST['name'];

            $list['user_id'] = $id;

            $list['upload_time'] = date('Y.m.d',time());

            Db::table('picture')->insert($list);

            return  $this->success('新增图片成功');

        } else {

            return  $this->error('新增图片失败');

        }

     }



}
